package top.meijhm.communitymanagement.common.auth.security;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import top.meijhm.communitymanagement.common.auth.filter.CaptchaFilter;
import top.meijhm.communitymanagement.common.auth.filter.JwtAuthenticationFilter;
import top.meijhm.communitymanagement.common.auth.handler.JWTLogoutSuccessHandler;
import top.meijhm.communitymanagement.common.auth.handler.JwtAccessDeniedHandler;
import top.meijhm.communitymanagement.common.auth.handler.LoginFailureHandler;
import top.meijhm.communitymanagement.common.auth.handler.LoginSuccessHandler;
import top.meijhm.communitymanagement.common.auth.jwt.JwtAuthenticationEntryPoint;
import top.meijhm.communitymanagement.common.auth.util.PasswordEncoder;


@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    LoginFailureHandler loginFailureHandler;
    @Autowired
    LoginSuccessHandler loginSuccessHandler;
    @Autowired
    CaptchaFilter captchaFilter;
    @Autowired
    JwtAuthenticationEntryPoint jwtAuthenticationEntryPoint;
    @Autowired
    JwtAccessDeniedHandler jwtAccessDeniedHandler;
    @Autowired
    JWTLogoutSuccessHandler jwtLogoutSuccessHandler;
//    @Autowired
//    JwtAuthenticationFilter jwtAuthenticationFilter;

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    JwtAuthenticationFilter jwtAuthenticationFilter() throws Exception {
        return new JwtAuthenticationFilter(authenticationManager());
    }

    private static final String[] URL_WHITELIST = {
            "/actuator",
            "/swagger-*",
            "/webjars/**",
            "/v2/api-docs",
            "/login",
            "/logout",
            "/captcha",
            "/favicon.ico",
            "/redis/save"
    };

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new PasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable()
                // 登录配置
                .formLogin()
                //.loginPage("/login").loginProcessingUrl("/login")
                //.usernameParameter("username").passwordParameter("password")
                .successHandler(loginSuccessHandler)
                .failureHandler(loginFailureHandler)
                .and()
                .logout()
                .logoutSuccessHandler(jwtLogoutSuccessHandler)
                // 禁用session
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                // 配置拦截规则
                .and()
                .authorizeRequests()
                // 跨域请求会先进行一次options请求
                .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                //.antMatchers(HttpMethod.OPTIONS, "/**").anonymous()  // 允许匿名访问
                //.antMatchers(URL_WHITELIST).permitAll()
                .antMatchers("/login/auth", "/captcha", "/redis/save").anonymous()
                .antMatchers(
                        HttpMethod.GET,
                        "/*.html",
                        "/**/*.html",
                        "/**/*.css",
                        "/**/*.js"
                ).permitAll()
                .antMatchers("/profile/**").anonymous()
                .antMatchers("/common/download**").anonymous()
                .antMatchers("/common/download/resource**").anonymous()
                .antMatchers("/swagger-ui.html").anonymous()
                .antMatchers("/swagger-ui/**").anonymous()
                .antMatchers("/swagger-resources/**").anonymous()
                .antMatchers("/webjars/**").anonymous()
                .antMatchers("/*/api-docs").anonymous()
                .antMatchers("/druid/**").anonymous()
                //增加srs的过滤名单 2020-6-2 dev-api/v1/srs/
                .antMatchers("/srs/v1/**").anonymous()
                .anyRequest().authenticated()
                // 异常处理器
                .and()
                .exceptionHandling()
                .authenticationEntryPoint(jwtAuthenticationEntryPoint)
                .accessDeniedHandler(jwtAccessDeniedHandler)
                // 配置自定义的过滤器
                .and()
                .addFilter(jwtAuthenticationFilter())
                //.addFilter(jwtAuthenticationFilter)
                // 验证码过滤器放在UsernamePassword过滤器之前
                .addFilterBefore(captchaFilter, UsernamePasswordAuthenticationFilter.class)
        ;
    }
//    @Override
//    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        auth.userDetailsService(userDetailService);
//    }

    @Override
    public void configure(WebSecurity web) {
        //利用ignore忽略拦截，否则post delete请求被拦截，报错403 forbidden
        web.ignoring().antMatchers(
                "/v2/api-docs",
                "/swagger-resources/configuration/ui",
                "/swagger-resources",
                "/swagger-resources/configuration/security",
                "/swagger-ui/index.html");
    }
}